import requests
from lxml import html
import json
import time
import re
def get_one_page(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
    }
    res = requests.get(url, headers=headers)
    if res.status_code == 200:
        # print(res.text)
        return res.text
    return None

def spider(offset):
    url = "https://maoyan.com/board/4?offset={}".format(offset)
    html_data = get_one_page(url)
    selector = html.fromstring(html_data)
    topper = selector.xpath('//dd')
    rank_list = []
    for movie in topper:

        rank = movie.xpath('i/text()')[0]
        print("排名:{}".format(rank))

        name = movie.xpath('div/div/div/p/a/@title')[0]
        print("《{}》".format(name))

        star = movie.xpath('div/div/div/p[@class="star"]/text()')[0].strip()
        print(star)

        time = movie.xpath('div/div/div/p[@class="releasetime"]/text()')[0]
        print(time)

        score1 = movie.xpath('div/div/div/p[@class="score"]/i[1]/text()')[0]
        print("评分:{}".format(score1), end='')
        score2 = movie.xpath('div/div/div/p[@class="score"]/i[2]/text()')[0]
        print("{}".format(score2))

        image = movie.xpath('a[@class="image-link"]/img/@data-src')[0]
        print(image)
        print("-"*20)

        rank_list.append({
            'rank': rank,
            'name': name,
            'star': star,
            'time': time,
            'score': score1+score2,
            'image': image
        })

    return rank_list

def write_to_file(content):

    with open('result.txt', 'a', encoding='utf-8') as f:
        print(type(json.dumps(content)))
        f.write(json.dumps(content, ensure_ascii=False)+'\n\n')

if __name__ == '__main__':
    #spider()
    for i in range(0, 100, 10):
        for item in spider(i):
            write_to_file(item)